<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Tixian;
use App\Http\Resources\TixianCollection;
use App\Http\Resources\EarningCollection;

class TixianController extends Controller
{
    //用户的提现/收益
    public function tixian($method,$model)
    {
        $userinfo = request()->user();
        if ($model == 'earnings') {
            return new EarningCollection(
                $userinfo->earnings()->orderBy('created_at','desc')->paginate(10)
            );
        }else{
            return new TixianCollection(
                $userinfo->tixians()->orderBy('created_at','desc')->paginate(10)
            );
        }
    }

    //绑定提现支付宝号
    public function alipay_account(Request $request)
    {
        $userinfo = request()->user();
        $data = $request->validate([
            'realname' => 'required',
            'alipay_account' => 'required'
        ]);
        $userinfo->update($data);
        return response(['status' => 1, 'message' => 'success']);
    }

    //提现验证码
    public function codevalidate(Request $request)
    {
        $userinfo = request()->user();
        $request->validate([
            'code' => 'required'
        ]);
        if (request('code') == Redis::get($userinfo->mobile)) {
            return response(['status' => '1', 'message' => '验证成功']);
        } else {
            return response(['status' => '0', 'message' => '验证失败']);
        }
    }

    //  申请提现
    public function shenqingtixian(Request $request)
    {
        $tixianmoney = request('tixianmoney');
        if ($tixianmoney < 100) {
            return response(['status' => 0, 'message' => '提现金额必须不小于100']);
        }
        $userinfo = request()->user();
        if ($userinfo->money < 100) {
            return response(['status' => 0, 'message' => '可提现金额不足']);
        }
        if ($userinfo->money < $tixianmoney) {
            return response(['status' => 0, 'message' => '可提现金额不足']);
        }
        $data['tixianmoney'] = $tixianmoney;
        $data['user_id'] = $userinfo->id;
        $data['realname'] = $userinfo->realname;
        $data['alipay_account'] = $userinfo->alipay_account;
        if (empty($data['realname']) && empty($data['alipay_account'])) {
            return response(['status' => 0, 'message' => '没绑定提现账号']);
        }
        DB::transaction(function () use ($data, $userinfo, $tixianmoney) {
            Tixian::create($data);
            $userinfo->update([
                'tixianmoney' => $userinfo->tixianmoney + $tixianmoney,
                'money' => $userinfo->money - $tixianmoney,
            ]);
        });
        $userinfo->notify(new \App\Notifications\Tixian(['message'=>'您刚刚申请了'.$tixianmoney.'元的提现，提现金额会在3个工作日内到账。']));
        return response(['status' => '1', 'message' => '申请成功']);
    }
}
